package com.baturu.mybatisminus.model;

import com.baturu.mybatisminus.util.StringUtils;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huangbin
 */
@Data
public class TableInfo implements Serializable {

    private static final long serialVersionUID = -7064652639197891493L;

    private String tableName;

    private String idProperty;

    private String idColumn;

    private Class<?> entityClass;

    private Class<?> idClass;

    /**
     * 可能加上mysql转义符``的表名，只有在表名为保留关键字时才会添加
     */
    private String escapedTableName;

    private String escapedIdProperty;

    private String escapedIdColumn;


    private String currentNamespace;

    private String selectColumnString;

    private List<FieldInfo> fieldList;

    //不包含id
    private List<FieldInfo> insertableFieldList;

    //不包含id
    private List<FieldInfo> updatableFieldList;

    private Set<String> propertySet;

    private Map<String, FieldInfo> propertyToFieldInfoMap;


    public String getStatementId(String sqlMethod) {
        return currentNamespace + "." + sqlMethod;
    }


    public boolean containsProperty(String property) {
        return propertySet.contains(property);
    }


    public FieldInfo getFieldInfo(String property) {
        if (StringUtils.isEmpty(property)) {
            return null;
        }
        return propertyToFieldInfoMap.get(property);
    }

    public String getSelectColumnString() {
        if (StringUtils.isNotEmpty(selectColumnString)) {
            return selectColumnString;
        }
        selectColumnString = getSelectColumnString(fieldList);
        return selectColumnString;
    }

    public String getSelectColumnString(Set<String> propertySet) {
        Assert.notEmpty(propertySet, "propertySet must not be empty!");
        List<FieldInfo> filterList = fieldList.stream()
                .filter(fieldInfo -> propertySet.contains(fieldInfo.getProperty())).collect(Collectors.toList());
        return getSelectColumnString(filterList);
    }


    private String getSelectColumnString(List<FieldInfo> fieldInfoList) {
        Assert.notEmpty(fieldInfoList, "fieldInfoList must not be null");
        StringBuilder sb = new StringBuilder(" ");
        for (FieldInfo fieldInfo : fieldInfoList) {
            if (fieldInfo.isPropertyColumnEqual()) {
                sb.append(fieldInfo.getEscapedColumn());
            } else {
                sb.append(fieldInfo.getEscapedColumn()).append(" AS ").append(fieldInfo.getEscapedProperty());
            }
            sb.append(",");
        }
        sb.setLength(sb.length() - 1);
        sb.append(" ");
        return sb.toString();
    }


}
